import React, { useState, useRef } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import {
  Upload,
  Image as ImageIcon,
  Trash2,
  Eye,
  Plus,
  X,
  FileImage,
  Download,
} from "lucide-react";
// import { UploadFile } from '@/integrations/Core';
import { UploadFileAPI } from "@/api/uploading";

export default function SiteLayoutUploader({ scheme, onUpdate }) {
  const [uploading, setUploading] = useState(false);
  const [selectedImage, setSelectedImage] = useState(null);
  const fileInputRef = useRef(null);
  const { toast } = useToast();

  const siteLayoutImages = scheme.siteLayoutPlanImages || [];

  const handleFileUpload = async (files) => {
    if (!files || files.length === 0) return;

    setUploading(true);
    try {
      const uploadPromises = Array.from(files).map(async (file) => {
        // 检查文件类型
        if (!file.type.startsWith("image/")) {
          throw new Error(`文件 ${file.name} 不是有效的图片格式`);
        }

        // 检查文件大小 (最大20MB)
        if (file.size > 20 * 1024 * 1024) {
          // Changed from 10MB to 20MB
          throw new Error(`文件 ${file.name} 超过20MB大小限制`);
        }

        // const { file_url } = await UploadFile({ file });
        const resFile = await UploadFileAPI.upload(file);
        let fileUrl = resFile.data;
        return fileUrl;
      });

      const newImages = await Promise.all(uploadPromises);
      const updatedImages = [...siteLayoutImages, ...newImages];

      onUpdate({ siteLayoutPlanImages: updatedImages });

      toast({
        title: "上传成功",
        description: `成功上传 ${newImages.length} 张图片`,
      });
    } catch (error) {
      console.error("图片上传失败:", error);
      toast({
        variant: "destructive",
        title: "上传失败",
        description: error.message || "图片上传时出现错误",
      });
    } finally {
      setUploading(false);
    }
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const files = e.dataTransfer.files;
    handleFileUpload(files);
  };

  const handleFileInputChange = (e) => {
    handleFileUpload(e.target.files);
    e.target.value = ""; // 清空input以允许重复上传同一文件
  };

  const handleRemoveImage = (imageId) => {
    const updatedImages = siteLayoutImages.filter(
      (img) => img.docId !== imageId
    );
    onUpdate({ siteLayoutPlanImages: updatedImages });

    toast({
      title: "删除成功",
      description: "图片已从方案中移除",
    });
  };

  const handleUpdateDescription = (imageId, remark) => {
    const updatedImages = siteLayoutImages.map((img) =>
      img.docId === imageId ? { ...img, remark } : img
    );
    onUpdate({ siteLayoutPlanImages: updatedImages });
  };

  const handleViewImage = (image) => {
    setSelectedImage(image);
  };

  const ImagePreviewModal = () => {
    if (!selectedImage) return null;

    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
        <div className="bg-white rounded-lg shadow-xl max-w-4xl max-h-[90vh] overflow-auto">
          <div className="p-4 border-b flex justify-between items-center">
            <h3 className="text-lg font-semibold">{selectedImage.docName}</h3>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setSelectedImage(null)}
            >
              <X className="w-5 h-5" />
            </Button>
          </div>
          <div className="p-4">
            <img
              src={selectedImage.docUrl}
              alt={selectedImage.docName}
              className="max-w-full max-h-[70vh] object-contain mx-auto"
            />
            {selectedImage.description && (
              <p className="mt-4 text-gray-600 text-center">
                {selectedImage.description}
              </p>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="mt-5">
      <div>
        <Label htmlFor="siteLayoutPlan">施工平面布置图</Label>
        <p className="text-sm text-gray-600">
          上传施工现场平面布置图，支持多张图片上传，可添加图片描述。
        </p>
      </div>
      <CardContent className="space-y-4 mt-5">
        {/* 上传区域 */}
        <div
          className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors cursor-pointer"
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          onClick={() => fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*"
            onChange={handleFileInputChange}
            className="hidden"
          />

          <div className="flex flex-col items-center gap-3">
            <div className="p-3 bg-blue-100 rounded-full">
              <Upload className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-lg font-medium text-gray-900">
                {uploading ? "上传中..." : "点击或拖拽上传图片"}
              </p>
              <p className="text-sm text-gray-500">
                支持 JPG、PNG、GIF 格式，单个文件最大20MB，支持多选{" "}
                {/* Changed from 10MB to 20MB */}
              </p>
            </div>
            {!uploading && (
              <Button variant="outline" className="mt-2">
                <Plus className="w-4 h-4 mr-2" />
                选择图片
              </Button>
            )}
          </div>
        </div>

        {/* 已上传图片列表 */}
        {siteLayoutImages.length > 0 && (
          <div className="space-y-4">
            <div
              className="flex items-center justify-between"
              onClick={() => {
                console.log(
                  siteLayoutImages,
                  "siteLayoutImagessiteLayoutImages"
                );
              }}
            >
              <h4
                className="font-medium text-gray-900"
                onClick={() => {
                  console.log(siteLayoutImages, "siteLayoutImages");
                }}
              >
                已上传图片 ({siteLayoutImages.length})
              </h4>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {siteLayoutImages.map((image) => (
                <div
                  key={image.docId}
                  className="border rounded-lg p-4 space-y-3"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2 flex-1 min-w-0">
                      <FileImage className="w-4 h-4 text-blue-500 flex-shrink-0" />
                      <span className="text-sm font-medium text-gray-900 truncate">
                        {image.docName}
                      </span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleViewImage(image)}
                        className="h-8 w-8"
                        title="预览图片"
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => window.open(image.docUrl, "_blank")}
                        className="h-8 w-8"
                        title="在新窗口打开"
                      >
                        <Download className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleRemoveImage(image.docId)}
                        className="h-8 w-8 text-red-500 hover:text-red-700"
                        title="删除图片"
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  <div className="aspect-video bg-gray-100 rounded-lg overflow-hidden">
                    <img
                      src={image.docUrl}
                      alt={image.docName}
                      className="w-full h-full object-cover cursor-pointer hover:opacity-90 transition-opacity"
                      onClick={() => handleViewImage(image)}
                    />
                  </div>

                  <div>
                    <Label
                      htmlFor={`desc-${image.docId}`}
                      className="text-xs text-gray-600"
                    >
                      图片描述 (可选)
                    </Label>
                    <Input
                      id={`desc-${image.docId}`}
                      value={image.remark || ""}
                      onChange={(e) =>
                        handleUpdateDescription(image.docId, e.target.value)
                      }
                      placeholder="为这张图片添加描述..."
                      className="mt-1 text-sm"
                    />
                  </div>

                  <p className="text-xs text-gray-400">
                    上传时间: {new Date(image.docUploadDate).toLocaleString()}
                  </p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 图片预览模态框 */}
        <ImagePreviewModal />
      </CardContent>
    </div>
  );
}
